package control;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import antlr.Token;

import com.oreilly.servlet.MultipartRequest;


import swimv2.ejb.remote.GestioneCapacitaRemote;
import swimv2.ejb.remote.RegistrazioneRemote;
import swimv2.ejb.util.GetBytesFromFile;
import swimv2.ejb.util.LoginToken;
import swimv2.ejb.entity.Capacita;
import util.HtmlUtil;

/**
 * Servlet implementation class FotoProfilo
 */
public class FotoProfilo extends Servlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see Servlet#Servlet()
     */
    public FotoProfilo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HtmlUtil.CompletaEdIncludi(request, response, "/WEB-INF/pages/fotoProfilo.jsp");
	}
	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			LoginToken tok = (LoginToken) request.getSession().getAttribute("LoginToken");
		    String username=tok.getUsername();
			Context jndiContext = new javax.naming.InitialContext();
			Object ref1 = jndiContext.lookup("Registrazione/remote");
			RegistrazioneRemote registrazioneRemote = (RegistrazioneRemote) PortableRemoteObject.narrow(ref1, RegistrazioneRemote.class);
			
			
			//request.setCharacterEncoding("UTF-8");
			MultipartRequest mrequest = new MultipartRequest(request,"./"); // dim. max di 1Mbyte
			
			
			
			File foto=mrequest.getFile("foto");
			byte[] fotoProfiloBytes=null;
			if(foto!=null) {
				//if( !( foto.getName().endsWith(".jpg") || foto.getName().endsWith(".jpeg") || foto.getName().endsWith(".png") || foto.getName().endsWith(".gif") ) )
				//	throw new RegistrazioneException("Estensione del file non corretta");
				fotoProfiloBytes = GetBytesFromFile.getBytesFromFile(foto);
			}
			
			registrazioneRemote.aggiornaFoto(username, fotoProfiloBytes);
			request.setAttribute("foto", fotoProfiloBytes);
			HtmlUtil.CompletaEdIncludi(request, response, "/WEB-INF/pages/fotoProfilo.jsp");
	   		return;
		}
		
		catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	

	

}
